package edu.colorado.karl.databases;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Manages the opening and closing of connections to the MySQL databases.
 * Creating and closing connections are done via static methods so the classes
 * requesting a database connection must track the state of that connection
 * on their own.  No state about open connections is maintained inside <code>
 * MySQLConnector</code>.
 * @author Michael Knudson
 * @version 3/2/08
 */
abstract public class MySQLConnector {
	//	Used for log4j logging
	private static final Log log = LogFactory.getLog(MySQLConnector.class);

	/**
	 * Sole constructor. (For invocation by subclass constructors, typically
	 * implicit.) All of this class' methods are static, there is no need to
	 * explicitly instantiate
	 * <code>MySQLConnector</code>.
	 */
	protected MySQLConnector() {
		
	}
	
	/**
	 * Attempts to create a connection to the specified database.
	 * @param database	The name of the database to connect to.
	 * @return if successful, a connection to the database, if unsuccessful 
	 * returns <code>null</code>.
	 */
	protected static Connection getConnection(String database) {
		try {
			String userName = "root";
			String password = "demo07";
			Class.forName ("com.mysql.jdbc.Driver").newInstance();
			Connection conn = DriverManager.getConnection (database, userName, password);
			if(conn != null) {
				log.debug("Database connection established to " + database);
			} else {
				log.warn("ERROR attempting to connect to database " + database);
			}
			return conn;
		}
		catch (Exception e) {
			log.warn("Cannot connect to database server for " + database, e);
			return null;
		}
	}
	
	/**
	 * Attempts to close an open connection to the specified database.
	 * @param c			The connection to close
	 * @param database	The name of the database <code>c</code> is connected to.
	 *	 				(used for logging)
	 */
	protected static void closeConnection(Connection c, String database) {
		if(c == null)
			throw new NullPointerException();
		try {
			c.close();
			log.debug("Database connection closed for " + database);
		} catch (SQLException e) {
			log.info("Warning: Exception occured while closing connection to " + database, e);
		}
	}
}
